package com.buddies.lottery.ui.lottery;

import android.text.TextUtils;

import com.buddies.lottery.App;
import com.buddies.lottery.base.BasePagerFragment;
import com.buddies.lottery.data.bean.LotteryCategory;
import com.buddies.lottery.data.result.PageResult;
import com.buddies.lottery.ui.MainActivity;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class LotteryFragment extends BasePagerFragment<LotteryContract.Presenter> implements LotteryContract.View {

    @Override
    public void initData() {
        mPresenter = new LotteryPresenter(this);
        super.initData();
    }

    @Override
    protected void initTabTextAndFragment() {
        mTabTexts.add("全部");
        mFragments.add(LotteryCategoryFragment.newInstance(0));

        String json = App.getInstance().getACache().getAsString("lottery_categories");
        if (!TextUtils.isEmpty(json)) {
            List<LotteryCategory> list = App.getGson().fromJson(json, new TypeToken<List<LotteryCategory>>(){}.getType());
            for (LotteryCategory category : list) {
                mTabTexts.add(category.name);
                mFragments.add(LotteryCategoryFragment.newInstance(category.id));
            }
        }
    }

    private void forceRefresh() {
        ((LotteryPresenter) mPresenter).loadLotteryCategoryList();
        showProgressDialog("正在加载");
    }

    @Override
    public void onResume() {
        super.onResume();

        forceRefreshIfNeed();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        forceRefreshIfNeed();
    }

    protected boolean isUserVisible() {
        return getUserVisibleHint() && getActivity() != null && ((MainActivity) getActivity()).getCurrentTab() == 1;
    }

    private void forceRefreshIfNeed() {
        if (isUserVisible() && mTabTexts.size() == 1) {
            forceRefresh();
        }
    }

    @Override
    public void onLotteryCategoryListLoaded(PageResult<LotteryCategory> response) {
        hideProgressDialog();
        List<LotteryCategory> list = response.list;
        if (list != null && !list.isEmpty()) {
            mTabTexts.clear();
            mFragments.clear();
            mTabTexts.add("全部");
            mFragments.add(LotteryCategoryFragment.newInstance(0));

            // 缓存分类
            App.getInstance().getACache().put("lottery_categories", App.getGson().toJson(list), 24 * 60 * 60);

            for (LotteryCategory category : list) {
                mTabTexts.add(category.name);
                mFragments.add(LotteryCategoryFragment.newInstance(category.id));
            }

            mPagerAdapter.notifyDataSetChanged();

            updateTabTextAndFragment();
        }
    }

    public int getCurrentTab() {
        return mViewPager.getCurrentItem();
    }

}
